<?php

namespace app\index\controller;

use addons\epay\library\Service;
use app\common\controller\Frontend;
use app\common\library\goods\Orders;
use app\common\model\goods\Category;
use app\common\model\Goods as GoodsModel;
use think\Exception;

/**
 * 充值
 */
class Goods extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['epay'];
    protected $noNeedRight = ['*'];
	protected $categoryModel,$goodsModel;

	public function _initialize(){
        parent::_initialize();
		$this->categoryModel = new Category();
		$this->goodsModel = new GoodsModel();
	}

    /**
     * 商品列表
     * @return string
     */
    public function index()
    {
		// 分类
		$category = $this->categoryModel->where(['status'=>'normal'])->select();
		foreach($category as &$item) {
			$item->goods = $this->goodsModel->where(['category_id' => $item->id, 'status' => 'normal'])->select();
		};
		$this->view->assign('category', $category);

        return $this->view->fetch();
    }

    /**
     * 创建订单并发起支付请求
     */
    public function submit()
    {
        $info = get_addon_info('epay');
        if (!$info || !$info['state']) {
            $this->error('请在后台插件管理安装微信支付宝整合插件后重试');
        }
        $goods_id = $this->request->request('goods_id/d');
        $paytype = $this->request->request('paytype');
        $config = get_addon_config('recharge');
        try {
            $response = Orders::submit($goods_id, $paytype ? $paytype : 'balance');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        return $response;
    }

    /**
     * 企业支付通知和回调
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            //判断是V2还是V3
            $data = \addons\epay\library\Service::isVersionV3() ? $pay->callback() : $pay->verify();
            try {
                //微信支付V3返回和V2不同
                if (\addons\epay\library\Service::isVersionV3() && $paytype === 'wechat') {
                    $data = $data['resource']['ciphertext'];
                    $data['total_fee'] = $data['amount']['total'];
                }

                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                Orders::settle($data['out_trade_no'], $payamount);
            } catch (Exception $e) {
                \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
            }

            //下面这句必须要执行,且在此之前不能有任何输出
            if (\addons\epay\library\Service::isVersionV3()) {
                return $pay->success()->getBody()->getContents();
            } else {
                return $pay->success()->send();
            }

        } else {
            $this->success("请返回网站查看支付状态!", "index/vip/viplist");
        }
    }
}
